<template>
  <Dialog
    title="修改密码"
    @closed="handleDialogClosed"
    @open="handleDialogOpen"
    @handle-confirm="handleConfirm"
  >
    <el-form
      ref="formEl"
      v-loading="formLoading"
      :model="passwordForm"
      :rules="rules"
      label-position="right"
      label-width="100px"
    >
      <el-form-item label="用户名">
        <p>{{ userName }}</p>
      </el-form-item>
      <el-form-item label="原密码" prop="currentPassword">
        <el-input v-model="passwordForm.currentPassword" show-password />
      </el-form-item>
      <el-form-item label="新密码" prop="newPassword">
        <el-input v-model="passwordForm.newPassword" show-password />
      </el-form-item>
      <el-form-item label="请重复密码" prop="confirmPassword">
        <el-input v-model="passwordForm.confirmPassword" show-password />
      </el-form-item>
    </el-form>
  </Dialog>
</template>

<script lang="ts" setup>
import { ElMessage } from 'element-plus'
import { computed, reactive, ref } from 'vue'

import Dialog from '@/components/Dialog/index.vue'
import { changePassword } from '@/http/common'
import piniaStore from '@/store'
import type { IElForm } from '@/types/element-plus'
import { validPassword } from '@/utils/validate'

const userName = computed(() => piniaStore.userStore.userName)

const validPassWords = (rule: any, value: any, callback: any) => {
  if (!validPassword(value)) {
    callback(
      new Error('密码必须包含大小写字母、数字和特殊字符（长度大于6位）！'),
    )
  }
  callback()
}
const validConfirmPassword = (rule: any, value: any, callback: any) => {
  if (passwordForm.value.confirmPassword !== passwordForm.value.newPassword) {
    callback(new Error('请确认两次密码一致！'))
  }
  callback()
}
interface EmitsType {
  (e: 'update:editId', value: number | null): void
  (e: 'success'): void
}
const emit = defineEmits<EmitsType>()

interface IPassWord {
  currentPassword: string
  newPassword: string
  confirmPassword: string
}
const passwordForm = ref<IPassWord>({
  currentPassword: '',
  newPassword: '',
  confirmPassword: '',
})

const rules = reactive({
  currentPassword: [
    { required: true, message: '请输入原密码', trigger: 'blur' },
  ],
  newPassword: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { validator: validPassWords, trigger: 'blur' },
  ],
  confirmPassword: [
    {
      required: true,
      message: '请再次输入密码',
      trigger: 'blur',
    },
    { validator: validConfirmPassword, trigger: 'blur' },
  ],
})

const formEl = ref<IElForm>()
const handleConfirm = async () => {
  try {
    await formEl.value?.validate()
    await changePassword({
      currentPassword: passwordForm.value.currentPassword,
      newPassword: passwordForm.value.confirmPassword,
    })
    ElMessage.success('保存成功')
    emit('success')
  } catch (err) {
    console.error(err)
  }
}
const formLoading = ref(false)
const handleDialogOpen = async () => {}
const handleDialogClosed = () => {
  formEl.value?.resetFields() // 清除表单数据
}
</script>

<style scoped></style>
